﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
namespace td.Core.Controls
{
    public partial class tdGridView<T> : DevExpress.XtraEditors.XtraUserControl
    {
        Dictionary<string, string> ColumnAlias = new Dictionary<string, string>();
        public event EventHandler RowCellClick;
        private int pagesize = 50000;
        private int PageCount = 0;
        private int currentPage = 0 ;
        private int CurrentPage
        {
            get
            {
                return this.currentPage;
            }
            set
            {
                this.currentPage = value;
                if (this.CurrentPageChanged != null) this.CurrentPageChanged(currentPage, EventArgs.Empty);
            }
        }
        public event EventHandler DataSourceChanged;
        public event EventHandler CurrentPageChanged;
        
        public int PageSize
        {
            get
            {
                return this.pagesize;
            }
            set
            {
                this.pagesize = value;
            }
        }
        IQueryable<T> dataSource;
        /// <summary>
        /// 设置GridControl的数据源，注意，该属性为IQueryable<T>类型，且必须经过orderby排序
        /// </summary>
        public IQueryable<T> DataSource
        {
            get
            {
                return dataSource;
            }
            set
            {
                this.dataSource = value;

                if (this.DisplayColumns != null)
                {
                    if (!this.IsInited)
                    {
                        this.IsInited = true;
                        initGridView(this.DisplayColumns);
                    }
                }

                if (this.DataSourceChanged != null)
                {
                    this.DataSourceChanged(DataSource, EventArgs.Empty);
                }
            }
        }
        void UpdateMsg()
        {
            this.labelControl1.Text = "共"+this.dataSource.Count()+"条记录，每页"+this.pagesize+"条，当前第"+(CurrentPage+1)+"页，共"+this.PageCount+"页";
        }
        void BindData()
        {
            int index = 0;
            if (DataSource == null) return;
            index = this.CurrentPage < 0 ? 0 : this.CurrentPage;
            var cc = (from c in DataSource select c).Skip(pagesize * index).Take(pagesize);
            this.gridControl1.DataSource = cc.ToList<T>();
             
        }
        /// <summary>
        /// 传入字符串为要显示的列的字段，以,分隔。
        /// </summary>
        public string DisplayColumns { get; set; }
        public string NonDisplayColumns { get; set; }
        private bool IsInited { get; set; }
        
        public tdGridView()
        {
            InitializeComponent();

            this.gridView1.OptionsBehavior.AutoPopulateColumns = false;

            this.gridView1.IndicatorWidth = 40;
            this.gridView1.CustomDrawRowIndicator += new DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventHandler(gridView1_CustomDrawRowIndicator);

            //隐藏表头的分组
            this.gridView1.OptionsView.ShowGroupPanel = false;
            if (this.DisplayColumns != null)
            {
                if (!this.IsInited)
                {
                    this.IsInited = true;
                    initGridView(this.DisplayColumns);
                }
            }

            BindData();
          
            this.DataSourceChanged += new EventHandler(tdGridView_DataSourceChanged);
            this.comboBoxEdit1.SelectedIndexChanged += new EventHandler(comboBoxEdit1_SelectedIndexChanged);
            this.CurrentPageChanged += new EventHandler(tdGridView_CurrentPageChanged);
        }
        /// <summary>
        /// 该事件处理函数用于显示行号。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle >= 0)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }
                else if (e.RowHandle < 0 && e.RowHandle > -1000)
                {
                    e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite;
                    e.Info.DisplayText = "G" + e.RowHandle.ToString();
                }
            }

        }
        /// <summary>
        /// 使用此函数，则必须先设置DisplayColumns 属性，GridView不会自动创建列，根据field传入的字符串生成列 
        /// </summary>
        /// <param name="field"></param>
        /// <param name="caption"></param>
        void initGridView(string field)
        {
            
            string[] Field = field.Split(',');
            for (int i = 0; i < Field.Length; i++)
            {
                this.gridView1.Columns.AddVisible(Field[i]);
            }
            if (this.NonDisplayColumns != null)
            {
                string[] n = this.NonDisplayColumns.Split(',');

                for (int i = 0; i < n.Length; i++)
                {
                    this.gridView1.Columns[n[i]].Visible = false;
                }
            }

            var e = this.ColumnAlias.GetEnumerator();
            while (e.MoveNext())
            {
                this.gridView1.Columns[e.Current.Key].Caption = e.Current.Value;
            }
        }
        /// <summary>
        /// 设置列的显示名称
        /// </summary>
        /// <param name="FieldName">字段名</param>
        /// <param name="Caption">显示名</param>
        public void AddColumnAlias(string FieldName, string Caption)
        {
            this.ColumnAlias.Add(FieldName, Caption);
        }
        void tdGridView_CurrentPageChanged(object sender, EventArgs e)
        {
            BindData();
            UpdateMsg();
        }

        void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.CurrentPage = this.comboBoxEdit1.SelectedIndex;
        }

        void tdGridView_DataSourceChanged(object sender, EventArgs e)
        {
            BindData();

            if (this.DataSource.Count() % pagesize == 0)
            {
                this.PageCount = this.DataSource.Count() / pagesize;
            }
            else
            {
                this.PageCount = this.DataSource.Count() / pagesize + 1;
            }
            this.comboBoxEdit1.Properties.Items.Clear();
            for(int  i = 1;i< PageCount+1;i++)
            {
                this.comboBoxEdit1.Properties.Items.Add(i);
            }
            this.comboBoxEdit1.SelectedIndex = 0;
            UpdateMsg();
        }
        /// <summary>
        /// 翻页按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClick(object sender, EventArgs e)
        {
            switch (((SimpleButton)sender).Text)
            {
                case "|<":
                    this.comboBoxEdit1.SelectedIndex = 0;
                    break;
                case "<":
                    if (this.comboBoxEdit1.SelectedIndex >=1)
                    {
                        this.comboBoxEdit1.SelectedIndex -= 1;
                    }
                    break;
                case ">":
                    if (this.comboBoxEdit1.SelectedIndex < PageCount - 1)
                    {
                        this.comboBoxEdit1.SelectedIndex += 1;
                    }
                    break;
                case ">|":
                    this.comboBoxEdit1.SelectedIndex = PageCount - 1;
                    break;
                default:
                    break;
            }
        }
    }
}
